import { Inject, Controller, Get, Post, Put,Files, Fields, Param } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { AnnService } from '../../service/admin/announcement.service';
import * as fs from 'fs';
import * as path from 'path';

@Controller('/api/admin')
export class APIController {
    @Inject()
    ctx: Context;

    @Inject()
    annService: AnnService;

    @Get('/announcement', { description: '获取公告栏' })
    async getannouncement() {
        console.log(13131242142154325325325);
        const result = await this.annService.getAllAnn()
        if(result.length!=0){
            for(var i = 0 ;i< result.length; i++){
              const fileName = result[i].image;
              const Annpic = fs.readFileSync(path.join(__dirname, '../../../public/upload/conn', fileName));
              result[i]["src"] = Annpic     
            } 
          }
        return { success: true, message: '获取所有公告栏成功', result }
    }

    @Post('/announcement', { description: '新增公告栏' })
    async addannouncement(@Files() files, @Fields() Fields) {
        console.log("files", files);
        console.log("Fields", Fields);
        const image = files
        // 指定图片存储的路径
        const filePath = path.join(__dirname, '../../../public/upload/conn', image[0].filename);
        // 将图片数据写入到指定的文件中
        fs.writeFileSync(filePath, fs.readFileSync(image[0].data));
        const info = {}
        info["title"]=Fields.title
        info["content"]=Fields.content
        info["image"]=image[0].filename
        console.log(info);
        const result = await this.annService.addAnn(info)
        return { success: true, message: '新增公告栏成功',result }
    }
    @Put('/announcement', { description: '更新公告栏' })
    async updateannouncement(@Files() files, @Fields() Fields) {
        const image = files
        // 指定图片存储的路径
        const filePath = path.join(__dirname, '../../../public/upload/conn', image[0].filename);
        // 将图片数据写入到指定的文件中
        fs.writeFileSync(filePath, fs.readFileSync(image[0].data));
        const info = {}
        info["id"]=Fields.id
        info["title"]=Fields.title
        info["content"]=Fields.content
        info["image"]=image[0].filename
        console.log(info);
        const result = await this.annService.updateAnn(info)
        return { success: true, message: '更新公告栏成功',result }
    }
    @Post('/deleteannouncement/:id', { description: '删除公告栏' })
    async deleteannouncement(@Param() Param) {
        const result = await this.annService.deleteAnn(Param.id)
        return { success: true, message: '删除成功', result }
    }
}